// import {getInfo, login, logout} from '@/api/login'
import { getToken, removeToken, setToken } from '@/utils/cookies'
// import {default as api} from '../../utils/api'
import store from '../../store'
import router from '../../router'
import { commonLogin, commongetInfo, commonLogOut } from '../../service/common'

const user = {
  state: {
    nickname: "",
    userId: "",
    avatar: 'https://www.gravatar.com/avatar/6560ed55e62396e40b34aac1e5041028',
    role: '',
    menus: [],
    permissions: [],
  },
  mutations: {
    SET_USER: (state, userInfo) => {
      state.nickname = userInfo.nickname;
      state.userId = userInfo.userId;
      state.role = userInfo.roleName ||'';
      state.menus = userInfo.menuList;
      state.permissions = userInfo.permissionList;
    },
    RESET_USER: (state) => {
      state.nickname = "";
      state.userId = "";
      state.role = '';
      state.menus = [];
      state.permissions = [];
    }
  },
  actions: {
    // 登录
    async Login({ commit, state }, loginForm) {
      const res = await commonLogin(loginForm)
      return res
    },
    // 获取用户信息 来确定加载权限页面
    async GetInfo({ commit, state }) {
      try {
        const res = await commongetInfo()
        console.log(res, '获取用户信息res')
        if (res.code == '200') {
         //储存用户信息
         await commit('SET_USER', res.data.userPermission);
         console.log(store.getters.nickname,'储存用户信 role是否已经设置')
         let userPermission = res.data.userPermission;
         await store.dispatch('GenerateRoutes', userPermission)
         router.addRoutes(store.getters.addRouters)
        }else {
          console.log('获取用户信息接口异常 清除token')
          sessionStorage.removeItem('token')
        }
      } catch (error) {
        console.log(error,'获取用户信息res失败')
        sessionStorage.removeItem('token')
      }
    },
    // 退出
    async LogOut({ commit }) {
      try {
        await commonLogOut()
        sessionStorage.removeItem('token')
        commit('RESET_USER')
      } catch (error) {
        sessionStorage.removeItem('token')
        commit('RESET_USER')
      }
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('RESET_USER')
        sessionStorage.removeItem('token')
        resolve()
      })
    }
  }
}
export default user
